<?php

class DefaultController extends Controller
{
	public $layout='//layouts/cms_layout';
	
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}
	
	
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('login','notify','encode'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('help','module','user','index', 'ajaxFillTree','settings','update','bio','list','csv','vote','tag','export'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	public function actionIndex($id = null)
	{
		//register assets
        $clientScript = Yii::app()->getClientScript(); 
        $baseUrl = $this->module->assetsUrl;
        $jplayer_skin = $this->module->jplayer_skin;
        
        $clientScript->registerCssFile($baseUrl . '/css/main.css');
        $clientScript->registerCssFile($baseUrl . '/css/style.css');
        
        $clientScript->registerCssFile($baseUrl . '/css/jRating.jquery.css');
        $clientScript->registerScriptFile($baseUrl . '/js/jRating.jquery.min.js');
        
        $clientScript->registerCssFile($baseUrl . '/css/jquery-ui.css');
        $clientScript->registerScriptFile($baseUrl . '/js/jquery-ui.min.js');
        $clientScript->registerCssFile($baseUrl . '/css/jquery-tagselector.css');
        $clientScript->registerScriptFile($baseUrl . '/js/jquery-tagselector.js');
        
        // Tipsy
        $clientScript->registerCssFile($baseUrl . '/extensions/tipsy/tipsy.css');
        $clientScript->registerScriptFile($baseUrl . '/extensions/tipsy/jquery.tipsy.js', CClientScript::POS_HEAD);
        $clientScript->registerScriptFile($baseUrl.'/js/swfobject.js');
        

    	$html = '
		$(document).ready(function() 
		{
			$(\'#north\').tipsy({gravity: \'n\'});
			$(\'#north1\').tipsy({gravity: \'n\'});
			$(\'#north2\').tipsy({gravity: \'n\'});
				  
			$(\'#nav-example-05\').click(function() 
			{
				$(\'.dropdown\').slideToggle(\'medium\', function() {});
			});
  		});';	
	
		// jPlayer videos
    	$clientScript->registerScript('initTipsy', $html);
    	    	    	
        $model = new Content();
        $videoGallery = $model->findByAttributes(array('name'=>'Video Gallery'));
		$videos = $model->with('contentFiles', 'contentStatus')->findAllByAttributes(array('parent_id'=>$videoGallery->id));

		$this->widget('application.modules.video.extensions.jPlayerWidget', 
		array('mediaArray'=>$videos, 'baseUrl'=>$baseUrl, 'jplayerSkin'=>$jplayer_skin));

		/*if(!empty($id))
			$videos = Content::model()->findAllByAttributes(array('parent_id'=>67), array('condition'=>'content_status_id='.$id) );
		else
			$videos = Content::model()->findAllByAttributes(array('parent_id'=>67));

*/
		if(!empty($_POST)){
			if(!empty($_POST['input'])){
				Yii::app()->session['sortParams'] = $_POST['input'];			
			}else{
				Yii::app()->session['sortParams'] = array('status_all' => 'on');
			}
		}
		
		$criteria = new CDbCriteria();
		        
        if(!empty($id))
        {
        	switch ($id) {
        		case Content::ACTION_STATE:           			
        			$criteria->select = '*';
			        $criteria->condition = 'parent_id = :pid AND content_status_id != :sid';
			        
			        $status = array();			       
			        if(isset(Yii::app()->session['sortParams']['status_all'])){
			        	$status = array(1,2,3,4,5);
			        }else{
				        if(isset(Yii::app()->session['sortParams']['status_rejected']))
				        	array_push($status, Content::STATUS_REJECTED);
				        if(isset(Yii::app()->session['sortParams']['status_approved']))
				        	array_push($status, Content::STATUS_APPROVED);
				        if(isset(Yii::app()->session['sortParams']['status_new']))
				        	array_push($status, Content::STATUS_NEW);
				        if(isset(Yii::app()->session['sortParams']['status_pending']))
				        	array_push($status, Content::STATUS_PENDING);
                                        if(isset(Yii::app()->session['sortParams']['status_promo']))
				        	array_push($status, Content::STATUS_PROMO);
			        }
			        $criteria->params = array (':pid'=>67, ':sid'=>1);	
			        $criteria->addInCondition('content_status_id', $status, "AND");		        		                			
			        $criteria->join = 'JOIN user_details ON user_details.content_id = t.id';
			        $criteria->order = 'user_details.state';	
			
			        break;
        		case Content::ACTION_VOTES:
					//SELECT * FROM content JOIN user_details ON user_details.content_id = content.id LEFT OUTER JOIN votes ON user_details.id = votes.user_details_id ORDER BY votes.num_votes DESC;
        			$criteria->select = '*';
			        $criteria->condition = 'parent_id = :pid AND content_status_id != :sid';
        			$criteria->join = 'JOIN user_details u ON u.content_id = t.id LEFT OUTER JOIN votes ON u.id = votes.user_details_id';
			        $criteria->order = 'votes.num_votes DESC';	
			        $criteria->params = array (':pid'=>67, ':sid'=>1);		
        			break;
        		case Content::ACTION_STARS:
					//SELECT * FROM content JOIN user_details ON user_details.content_id = content.id LEFT OUTER JOIN votes ON user_details.id = votes.user_details_id ORDER BY votes.num_votes DESC;
        			$criteria->select = '*';
			        $criteria->condition = 'parent_id = :pid AND content_status_id != :sid';
        			$criteria->join = 'JOIN user_details u ON u.content_id = t.id LEFT OUTER JOIN votes ON u.id = votes.user_details_id';
			        $criteria->order = '(votes.score_votes/votes.num_votes) DESC';	
			        $criteria->params = array (':pid'=>67, ':sid'=>1);		
        			break;
        		default:
        			//SELECT * FROM content JOIN user_details ON user_details.content_id = content.id JOIN tags ON user_details.id = tags.user_details_id;
        			$criteria->condition = 'content_status_id = :sid AND parent_id = :pid';
        			$criteria->params = array (':sid'=>$id, ':pid'=>67);
        		break;
        	}        	
        }else{
        	$criteria->condition = 'parent_id = :pid AND content_status_id != :sid';
        	$criteria->params = array (':pid'=>67, ':sid'=>1);
        	$criteria->order = "modified_date";
        }
       
        $item_count = Content::model()->count($criteria);                
        $pages = new CPagination($item_count);
        $pages->setPageSize(9);
        $pages->applyLimit($criteria);  
        $vids = Content::model()->findAll($criteria);
		
		// Render index
  		$this->render('index', array('videos'=>$vids, 'pages' => $pages));	
	}
		
	public function actionUpdate()
	{		
		if(isset($_POST['ContentStatus']))
                {
                        $status = $_GET['status'];
                        foreach ($_POST['ContentStatus'] as $key=>$value)
                        {    		
                                $record = Content::model()->findByPk($key);
                                if($status == Content::ACTION_DELETE){
                                        $record->deleted = 1;
                                        $record->save(); 
                                }
                                elseif($status == Content::ACTION_ENCODE){
                                        $model = UserDetails::model()->findByAttributes(array('content_id'=>$record->id));
                                        $explode = explode('/', $model->videopath);
                                        //$this->redirect('/video/default/encode?videoFile='.$explode[count($explode)-1]);
                                        $this->_encode($explode[count($explode)-1]);
                                }   			
                                else{
                                        $record->content_status_id = $status;
                                        $record->save();	
                                }    			
                        }
                }		
		$this->redirect('/video/default');
	}
	
	public function actionEncode()
	{
		$file = $_GET['videoFile'];
		$this->_encode($file);
		/*if(!empty($file))
		{
			$videoEncoder = New ZencoderVideoEncoder();
			$videoEncoder->sendRequest($file);
		}*/
	}
	
	private function _encode($file)
	{
		$videoEncoder = New ZencoderVideoEncoder();
		$videoEncoder->sendRequest($file);
	} 
	
	public function actionNotify()
	{
		$videoEncoder = New ZencoderVideoEncoder();
		$notification = $videoEncoder->handleNotification();
		if(!empty($notification))
		{
			$explode = explode('/',$notification->output->url);
			$filename = Content::getFileName($explode[count($explode)-1]);
			$content = Content::model()->find("name like '".$filename.".%'");
			$content->content_status_id = Content::STATUS_NEW;
			$content->name = $filename.ZencoderVideoEncoder::OUTPUT_FORMAT;
			$content->save();
			
			$contentFile = ContentFile::model()->findByAttributes(array('content_id'=>$content->id));
			$contentFile->file_name = $filename.ZencoderVideoEncoder::OUTPUT_FORMAT;
			$contentFile->save();
		};
		
	}
	
	public function processRow($row)
	{
		//Removes tabs, new lines and double space
		$row['address'] = preg_replace(array("/\t/", "/\s{2,}/", "/\n/"), array("", " ", " "), $row['address']);
		$row['about'] = preg_replace(array("/\t/", "/\s{2,}/", "/\n/"), array("", " ", " "), $row['about']);     
		return $row;
	}
	
	public function actionCsv()
	{
		Yii::import('ext.CSVExport');
		// create a function in your model like search() that would return
                                                
		//$provider = Yii::app()->db->createCommand('select * from user_details')->queryAll();
                $provider = Yii::app()->db->createCommand('SELECT * FROM content LEFT JOIN user_details ON user_details.content_id = content.id WHERE content.parent_id=67 AND content.content_status_id != 1')->queryAll();
		$csv = new CSVExport($provider);
		$csv->callback = array($this, 'processRow');
		$csv->headers = UserDetails::model()->attributeLabels();
		 
		$content = $csv->toCSV(null,',', '"');
		Yii::app()->getRequest()->sendFile('export.csv', $content, "text/csv", false);
		exit;
	}
	
	public function actionVote()
	{		
		if(isset($_POST['action']))
		{		
			$success = true;	
			$id = intval($_POST['idBox']);
			$score = round(floatval($_POST['rate'])*2)/2;			
			
			$model = Votes::model()->findByAttributes(array('user_details_id' => $id));		
			if(!$model)
				$model = new Votes;
				
			$model->user_details_id = $id;
			$model->num_votes = !empty($model->num_votes)? $model->num_votes+1 : 1; 
			$model->score_votes = !empty($model->num_votes)? $model->score_votes+$score : $score; 
			$model->save();		
		}
		
			$aResponse['message'] = '';
			$aResponse['message'] = 'Your rate has been successfuly recorded. Thanks for your rate :)';
			echo json_encode($aResponse);	
	}
	
	
	public function actionList()
	{
		$model = UserDetails::model()->findAll();
		$this->render('list',array('models'=>$model));		
	}
	
	public function actionExport()
	{
		$myFile = Yii::app()->basePath."/../media/export/my.html";
		$htmlContent = file_get_contents(Yii::app()->basePath."/../media/export/index.html");
		$replaceContent = file_get_contents(Yii::app()->basePath."/../media/export/content.html");
		
		$models = Content::model()->findByAttributes(array('parent_id'=> Content::VIDEO_ID));
		
		foreach ($models as $model) {
			$replaceContent .= $replaceContent;
		}
				
		$htmlContent = str_replace("<::content::>", $replaceContent, $htmlContent);
		$fh = fopen($myFile, 'w+');		
		fwrite($fh, $htmlContent);
		fclose($fh);
		exit;		
	}
	
    public function actionBio($id = null){
            if($id != null){
                $user = UserDetails::model()->findByPk($id);
                if($user){
                    
                    if(Yii::app()->request->isAjaxRequest){
                        $this->renderPartial('bio-ajax', array('user'=>$user));	
                    }
                    else{
                        $this->render('bio', array('user'=>$user));	
                    }
                }
                else{
                    print_r('User not found');
                    print_r($id);
                }
            }
            else{
                print_r('no id yet');//no user id. run for the hills.
            }
    }
    
    public function actionTag($id=null, $tag=null, $remove=false)
    {
    	if(!empty($id))
    	{
    		if($remove == 'true'){
    			$tagModel=Tags::model()->findByAttributes(array('user_details_id' => $id));
				$tagModel->delete();
    		}else{
	    		$tagModel = Tags::model()->findByAttributes(array('user_details_id' => $id));
	    		if(!$tagModel)
	    			$tagModel = New Tags;
	    			
	    		$tagModel->tags = $tag;
	    		$tagModel->user_details_id = $id;
	    		$tagModel->save();
    		}
    	}  
    }
}